

import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:fun4live/core/liveMessage.dart';
import 'package:fun4live/pages/live_room/player/player_controller.dart';
import 'package:get/get.dart';
import 'package:fun4live/controller/sites.dart';
import 'package:fun4live/controller/log.dart';
import 'package:fun4live/core/liveRoomDetail.dart';
import 'package:fun4live/core/livePlayQuality.dart';
import 'package:fun4live/controller/constant.dart';
class LiveRoomController extends PlayerController with WidgetsBindingObserver{
  final Site pSite;
  final String pRoomId;
  LiveRoomController({
    required this.pSite,
    required this.pRoomId,
  }){
    rxSite = pSite.obs;
    rxRoomId = pRoomId.obs;

  }

  late Rx<Site> rxSite;
  Site get site => rxSite.value;
  late Rx<String> rxRoomId;
  String get roomId => rxRoomId.value;
  var liveStatus = false.obs;
  Rx<LiveRoomDetail?> detail = Rx<LiveRoomDetail?>(null);

  /// 滚动控制
  final ScrollController scrollController = ScrollController();

  /// 聊天信息
  RxList<liveMessage> messages = RxList<liveMessage>();

  /// 清晰度数据
  RxList<LivePlayQuality> qualites = RxList<LivePlayQuality>();

  /// 当前清晰度
  var currentQuality = -1;
  var currentQualityInfo = "".obs;

  /// 线路数据
  RxList<String> playUrls = RxList<String>();

  /// 当前线路
  var currentLineIndex = -1;
  var currentLineInfo = "".obs;

  /// 退出倒计时
  var countdown = 60.obs;

  //Timer? autoExitTimer;

  @override
  void onInit(){
    WidgetsBinding.instance.addObserver(this);
    currentQuality = 0;
    print("#####onInit\n");
    loadData();
    super.onInit();

  }
  @override
  void didChangeAppLifecycleState(AppLifecycleState state){
    super.didChangeAppLifecycleState(state);
    if(state == AppLifecycleState.paused)
    {
      Log.d("进入后台");
    }
    else if (state == AppLifecycleState.resumed) {
      Log.d("返回前台");
      //isBackground = false;
    }
  }
  @override
  void onClose(){
    WidgetsBinding.instance.removeObserver(this);
    super.onClose();
  }

  ///加载直播间信息
  void loadData()async{
    print("###loadData\n");
    try{
          print("###loadData------------1(roomId:${roomId})\n");
      //SmartDialog.showLoading(msg: "");
       detail.value = await site.liveSite_.getRoomDetail(roomId: roomId);
             print("###loadData------------2\n");
        var playQualites =
          await site.liveSite_.getPlayQualites(detail: detail.value!);
        if (playQualites.isEmpty) {
                print("###loadData------------3\n");
        SmartDialog.showToast("无法读取播放清晰度");
        return;
      }
            print("###loadData------------4\n");
      qualites.value = playQualites;
      getPlayUrl();
    }catch(e){
      SmartDialog.showToast(e.toString());
    }finally{
      print("##### finall error\n");
      SmartDialog.dismiss(status: SmartStatus.loading);
    }
  }

  void getPlayUrl() async{
    print("get urls");
    playUrls.clear();
    currentQualityInfo.value = qualites[currentQuality].quality;
    currentLineInfo.value = "";
    currentLineIndex = -1;
    var playUrl = await site.liveSite_
        .getPlayUrls(detail: detail.value!, quality: qualites[currentQuality]);
    if (playUrl.isEmpty) {
      SmartDialog.showToast("无法读取播放地址");
      return;
    }
    playUrls.value = playUrl;
    currentLineIndex = 0;
    currentLineInfo.value = "线路${currentLineIndex + 1}";
    //重置错误次数
    //mediaErrorRetryCount = 0;
    setPlayer();
  }
  void setPlayer() async {
    currentLineInfo.value = "线路${currentLineIndex + 1}";
    errorMsg.value = "";
    Map<String, String> headers = {};
    if (site.id == Constant.kBiliBili) {
      headers = {
        "referer": "https://live.bilibili.com",
        "user-agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.1901.188"
      };
    } else if (site.id == Constant.kHuya) {
      headers = {
        "referer": "https://www.huya.com",
        "user-agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0"
      };
    }

    //player.open(
    //  Media(
    //    playUrls[currentLineIndex],
    //    httpHeaders: headers,
    //  ),
    //);
    print("---:${playUrls[currentLineIndex]}");
    player.setDataSource(playUrls[currentLineIndex],autoPlay: true);

    Log.d("播放链接\r\n：${playUrls[currentLineIndex]}");
  }
}